package com.ykq.permission.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ykq.permission.mapper.PermissionMapper;
import com.ykq.permission.service.PermissionService;
import com.ykq.pojo.entity.Permission;
import com.ykq.pojo.entity.User;
import com.ykq.pojo.vo.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: qy151-education-parent
 * @description:
 * @author: 闫克起2
 * @create: 2022-08-29 11:23
 **/
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public List<String> selectPermissionByUserid(String userid) {
        List<String> permissions = permissionMapper.selectPermissionByUserid(userid);
        return permissions;
    }

    @Override
    public CommonResult selectLeftPermission(String token) {
        String s = redisTemplate.opsForValue().get(token);
        Map map = JSON.parseObject(s, Map.class);
        JSONObject user = (JSONObject) map.get("user");
        String id = user.getString("id");
        List<Permission> permissionList = permissionMapper.selectLeftPermission(id);

        //设置层级关系
        List<Permission> firstMenus = new ArrayList<>();
        for (Permission first : permissionList) {
            //int
            if (first.getPid().equals("1")) {
                firstMenus.add(first);
            }
        }


        //为一级菜单设置二级菜单
        for (Permission first : firstMenus) {
            //根据一级菜单id 查询 该菜单得二级菜单。如果出现不确定有几级菜单 那么我们可以使用方法得递归调用
            first.setChildren(findChildren(permissionList, first.getId()));

        }
        return new CommonResult(2000,"查询成功",firstMenus);
    }
    //方法递归
    private List<Permission> findChildren(List<Permission> permissionList, String id) {
        List<Permission> children = new ArrayList<>();
        for (Permission p : permissionList) {
            if (p.getPid().equals(id)) {
                children.add(p);
            }
        }


        for (Permission child : children) {
            child.setChildren(findChildren(permissionList, child.getId()));
        }

        return children;

    }
}
























